package org.lewis.man.controllers;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.lewis.common.domain.EmailTask;
import org.lewis.common.domain.User;
import org.lewis.common.domain.VCode;
import org.lewis.common.email.EmailService;
import org.lewis.common.service.UserService;
import org.lewis.common.service.VCodeService;
import org.lewis.common.utils.WebUtils;

import com.google.code.kaptcha.Constants;
import com.tocersoft.framework.core.annotations.Controller;
import com.tocersoft.framework.core.annotations.Injection;
import com.tocersoft.framework.web.HttpUtils;
import com.tocersoft.framework.web.annotations.Mapping;
import com.tocersoft.framework.web.annotations.NameSpace;
import com.tocersoft.framework.web.renderer.Renderer;
import com.tocersoft.framework.web.renderer.TemplateRenderer;
import com.tocersoft.framework.web.renderer.TextRenderer;

/**
 * 用户注册
 * 
 * @author taiqichao
 * 
 */
@Controller
@NameSpace("/accounts")
public class AccountRegisterController {

	private final static String VIEWBASEPATH = "/WEB-INF/views/accounts";

	Log log = LogFactory.getLog(AccountRegisterController.class);

	@Injection("userService")
	private UserService userService;

	@Injection
	private EmailService emailService;
	
	@Injection
	private VCodeService vcodeService;

	@Mapping("/register")
	public Renderer register() throws Exception {
		Map<String, Object> model = new HashMap<String, Object>();

		if (WebUtils.isPost()) {
			// 校验tokenid
			String clientTokenId = WebUtils.getParameter("tokenid");
			String sessionTokenId = (String) WebUtils.getSession()
					.getAttribute("tokenid");
			if (!clientTokenId.equals(sessionTokenId)) {
				// 生成tokenid
				WebUtils.getSession().setAttribute("tokenid",
						UUID.randomUUID().toString());
				return new TemplateRenderer(VIEWBASEPATH
						+ "/register.vm");
			}

			String email = WebUtils.getParameter("form_email");
			String password = WebUtils.getParameter("form_password");
			String name = WebUtils.getParameter("form_name");
			String captcha = WebUtils.getParameter("captcha-solution");
			// 客户端输入校验
			if (StringUtils.isEmpty(email) || StringUtils.isEmpty(password)
					|| StringUtils.isEmpty(name)
					|| StringUtils.isEmpty(captcha)) {
				model.put("msg", "请将信息输入完整");
				return new TemplateRenderer(VIEWBASEPATH
						+ "/register.vm", model);
			}

			// 校验验证码
			String sessionCaptcha = (String) WebUtils.getSession()
					.getAttribute(Constants.KAPTCHA_SESSION_KEY);
			if (!captcha.trim().toLowerCase().equals(sessionCaptcha)) {
				model.put("msg", "验证码输入错误");
				return new TemplateRenderer(VIEWBASEPATH
						+ "/register.vm", model);
			}

			// 校验邮箱
			User user = userService.getUserByEmail(email);
			if (user != null) {
				model.put("msg", "该邮箱已经注册过了");
				return new TemplateRenderer(VIEWBASEPATH
						+ "/register.vm", model);
			}

			// 校验姓名
			User userName = userService.getUserByName(name);
			if (userName != null) {
				model.put("msg", "该昵称已经存在了，换个吧");
				return new TemplateRenderer(VIEWBASEPATH
						+ "/register.vm", model);
			}

			// 创建用户
			User newUser = new User();
			newUser.setCreateTime(new Date());
			newUser.setEmail(email);
			newUser.setName(name);
			newUser.setPassword(password);
			newUser.setStatus(0);
			// 持久化
			long uid = userService.createUser(newUser);
			newUser.setId(uid);

			// 发邮件
			sendEmail(newUser);

			model.put("email", newUser.getEmail());

			// 移除tokenid
			WebUtils.getSession().removeAttribute("tokenid");

			return new TemplateRenderer(VIEWBASEPATH + "/register_success.vm",
					model);
		} else {// 跳转到注册页
			// 生成tokenid
			WebUtils.getSession().setAttribute("tokenid",
					UUID.randomUUID().toString());
			return new TemplateRenderer(VIEWBASEPATH + "/register.vm");
		}

	}

	/**
	 * 返回发送邮件校验页面片段
	 * 
	 * @return
	 */
	@Mapping("/captcha_form")
	public Renderer toSendEmail() {
		return new TemplateRenderer(VIEWBASEPATH + "/resend_email.vm");
	}

	/**
	 * 重新发送邮件
	 * 
	 * @return
	 */
	@Mapping("/doSendEmail")
	public Renderer doSendEmail() {
		String inputCaptcha = WebUtils.getParameter("captcha");
		String email = WebUtils.getParameter("email");
		// 校验验证码
		String sessionCaptcha = (String) WebUtils.getSession().getAttribute(
				Constants.KAPTCHA_SESSION_KEY);
		if (!inputCaptcha.trim().toLowerCase().equals(sessionCaptcha)) {
			return new TextRenderer("E-1");
		}

		User user = userService.getUserByEmail(email);

		if (user != null && user.getStatus() == 0) {
			this.sendEmail(user);
			return new TextRenderer("S-1");
		}

		return new TextRenderer("E-2");

	}

	/**
	 * 发邮件
	 * 
	 * @param newUser
	 */
	private void sendEmail(User newUser) {
		String templateFile = "/WEB-INF/views/common/email.vm";
		String emailTitle = "请激活您的账户";
		String emailSendTo = newUser.getEmail();
		Map<String, Object> data = new HashMap<String, Object>();
		String code=null;
		VCode vcode=vcodeService.getByCode(newUser.getId(),VCode.TYPE.EMAILACT.name());
		if(null!=vcode){
			code=vcode.getCode();
		}else{
			code=UUID.randomUUID().toString();
			vcode=new VCode();
			vcode.setCode(code);
			vcode.setType(VCode.TYPE.EMAILACT.name());
			vcode.setUid(newUser.getId());
			vcodeService.addVCode(vcode);
		}
		String actUrl = HttpUtils.getContentPath() + "/accounts/activate/" + code;
		data.put("url", actUrl);
		data.put("name", newUser.getName());
		data.put("base", HttpUtils.getContentPath());
		emailService.sendEmail(EmailTask.TYPE.account.name(),EmailTask.SENDTYPE.immediately.name(),templateFile, emailTitle, emailSendTo, data);
	}

}
